import React, { useCallback, useEffect, useMemo } from "react";
import { Form, Space } from "antd";
import { Button } from "antd";
import Group, { TabGroupRender } from "./group";
import styles from "./index.module.less";
import { getInitValues } from "../core";
// 按是否是标签页先 设计分类

const FunFormInterpreter = ({ schema }: { schema: FunFormSchema }) => {
  const [form] = Form.useForm();
  const list = useMemo(() => {
    let result: Array<Array<FunFormGroup> | FunFormGroup> = [];
    let tmp: Array<FunFormGroup> = [];
    const { groups } = schema;
    let tabsKey = -1;
    for (let i = 0; i < groups.length; i++) {
      if (groups[i].border === 3) {
        if (tabsKey === -1) tabsKey = i;
        tmp.push(groups[i]);
      } else {
        result.push(groups[i]);
      }
    }
    tabsKey > -1 && result.splice(tabsKey, 0, tmp);
    return result;
  }, [schema]);

  const onSubmit = useCallback(() => {
    form
      .validateFields()
      .then((value: any) => {
        console.log(value);
      })
      .catch((err: Error) => {
        console.log(err);
      });
  }, [form]);

  useEffect(() => {
    form.resetFields();
  }, [schema, form]);

  return (
    <div className={styles.DndForm}>
      <Form
        onFinish={onSubmit}
        form={form}
        initialValues={getInitValues(schema).formSchama}
      >
        {list.map((item, i) => {
          if (Array.isArray(item)) {
            return <TabGroupRender key={"tabs_" + i} groups={item} />;
          } else {
            return <Group key={item.uuid} group={item}></Group>;
          }
        })}

        <Form.Item noStyle>
          <div className={styles.btns}>
            <Space>
              {schema.buttonGroups.map((btn) => {
                return (
                  <Button
                    htmlType={btn.isSystemBtn ? "submit" : "button"}
                    key={btn.uuid}
                    type={btn.isHieghtLight ? "primary" : "default"}
                  >
                    {btn.title}
                  </Button>
                );
              })}
            </Space>
          </div>
        </Form.Item>
      </Form>
    </div>
  );
};

export default FunFormInterpreter;
